package managedbean.IT;

import entity.AccessControl;
import entity.AccessRole;
import java.text.SimpleDateFormat;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.event.ActionEvent;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.util.Date;
import javax.ejb.EJB;
import session.stateless.EmployeeSessionBeanLocal;
import javax.faces.bean.ManagedProperty;
import java.util.Calendar;
import managedbean.UserSessionManagerBean;
import entity.Employee;
import java.util.ArrayList;
import java.util.HashSet;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import managedbean.EmailManager;
import session.stateless.LogSessionBeanLocal;

@ManagedBean(name = "employeeManagerBean")
@RequestScoped
public class EmployeeManagerBean {

    @ManagedProperty(value = "#{userSessionManagerBean}")
    private UserSessionManagerBean userSessionManagerBean;
    @EJB
    EmployeeSessionBeanLocal employeeSessionBeanLocal;
    @EJB
    private LogSessionBeanLocal logSessionBeanLocal;
    private String userId;
    private String userPassword;
    private String name;
    private Integer contactOffice;
    private Integer contactMobile;
    private String emailAddress;
    private String department;
    private String accountStatus;
    @Temporal(value = TemporalType.DATE)
    private Date passwordExpiry;
    private Integer invalidCounter;
    private String designation;
    private String selectedUserId;
    private ArrayList<String> accounts;
    @Temporal(value = TemporalType.DATE)
    private String dob;
    private String loadUpdateEmployee;
    private String loadSearchEmployee;
    private String loadUserAC;
    private String request;
    private static Employee employee;
    private ArrayList<Employee> employees;
    private String asroles;
    private String ascontrol;

    public EmployeeManagerBean() {
    }

    //Page onload
    public String getLoadSearchEmployee() {
        String temp = (String) FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("request");

        if (temp != null) {
            userSessionManagerBean.setSelectedItem((String) temp + ".xhtml");

            try {
                FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort() + "/MerlionERP-war/Web_IT/searchEmployee.xhtml");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        request = (String) userSessionManagerBean.getSelectedItem();
        employees = employeeSessionBeanLocal.getEmployees();

        return null;
    }

    public String getLoadUpdateEmployee() {
        try {
            employee = (Employee) userSessionManagerBean.getSelectedItem();
            userId = employee.getUserId();
            name = employee.getName();
            department = employee.getDepartment();
            designation = employee.getDesignation();
            contactOffice = employee.getContactOffice();
            contactMobile = employee.getContactMobile();
            emailAddress = employee.getEmailAddress();
            userPassword = employee.getUserPassword();
            accountStatus = employee.getAccountStatus();
            passwordExpiry = employee.getPasswordExpiry();
            invalidCounter = employee.getInvalidCounter();

            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

            dob = sdf.format(employee.getDob());
        } catch (Exception exception) {
            exception.printStackTrace();
            try {

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort()
                        + "/MerlionERP-war/searchEmployee.xhtml?request=updateEmployee");
            } catch (Exception ex) {
            }
        }

        return null;
    }

// <editor-fold defaultstate="collapsed" desc="Getter & Setter methods. Click on the + sign on the left to edit the code.">
    /**
     * @return the employee
     */
    public Employee getEmployee() {
        return employee;
    }

    /**
     * @param employee the employee to set
     */
    public void setEmployee(Employee employee) {
        this.employee = employee;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getContactOffice() {
        return contactOffice;
    }

    public void setContactOffice(Integer contactOffice) {
        this.contactOffice = contactOffice;
    }

    public Integer getContactMobile() {
        return contactMobile;
    }

    public void setContactMobile(Integer contactMobile) {
        this.contactMobile = contactMobile;
    }

    public String getEmailAddress() {
        return emailAddress;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public String getAccountStatus() {
        return accountStatus;
    }

    public void setAccountStatus(String accountStatus) {
        this.accountStatus = accountStatus;
    }

    public Date getPasswordExpiry() {
        return passwordExpiry;
    }

    public void setPasswordExpiry(Date passwordExpiry) {
        this.passwordExpiry = passwordExpiry;
    }

    public Integer getInvalidCounter() {
        return invalidCounter;
    }

    public void setInvalidCounter(Integer invalidCounter) {
        this.invalidCounter = invalidCounter;
    }

    public String getDesignation() {
        return designation;
    }

    public void setDesignation(String designation) {
        this.designation = designation;
    }

    public UserSessionManagerBean getUserSessionManagerBean() {
        return userSessionManagerBean;
    }

    public void setUserSessionManagerBean(UserSessionManagerBean userSessionManagerBean) {
        this.userSessionManagerBean = userSessionManagerBean;
    }

    public String getDob() {
        return dob;
    }

    public void setDob(String dob) {
        this.dob = dob;
    }

    public String getSelectedUserId() {
        return selectedUserId;
    }

    public void setSelectedUserId(String selectedUserId) {
        this.selectedUserId = selectedUserId;
    }

    public ArrayList<String> getAccounts() {
        return accounts;
    }

    public void setAccounts(ArrayList<String> accounts) {
        this.accounts = accounts;
    }

    /**
     * @return the employees
     */
    public ArrayList<Employee> getEmployees() {
        return employees;
    }

    /**
     * @param employees the employees to set
     */
    public void setEmployees(ArrayList<Employee> employees) {
        this.employees = employees;
    }

    public void setLoadSearchEmployee(String loadSearchEmployee) {
        this.loadSearchEmployee = loadSearchEmployee;
    }

    public void setLoadUpdateEmployee(String loadUpdateEmployee) {
        this.loadUpdateEmployee = loadUpdateEmployee;
    }

    /**
     * @return the asroles
     */
    public String getAsroles() {
        return asroles;
    }

    /**
     * @param asroles the asroles to set
     */
    public void setAsroles(String asroles) {
        this.asroles = asroles;
    }

    /**
     * @return the ascontrol
     */
    public String getAscontrol() {
        return ascontrol;
    }

    /**
     * @param ascontrol the ascontrol to set
     */
    public void setAscontrol(String ascontrol) {
        this.ascontrol = ascontrol;
    }

// </editor-fold>
    //Page methods
    public void addEmployee(ActionEvent event) {
        employee = employeeSessionBeanLocal.getEmployee(userId);

        if (employee == null) {
            setUserPassword(Long.toHexString(Double.doubleToLongBits(Math.random())).substring(0, 8));
            setAccountStatus("ACTIVE");
            Calendar cal = Calendar.getInstance();
            Date d = new Date();
            cal.setTime(d);
            setPasswordExpiry(d);
            setInvalidCounter(0);

            try {
                String items[] = dob.split("/");
                dob = items[2] + "/" + items[1] + "/" + items[0];

                System.out.println(dob);

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
                Date e = sdf.parse(dob);

                employeeSessionBeanLocal.addEmployee(userId, userPassword, name, contactOffice, contactMobile, emailAddress, department, accountStatus, passwordExpiry, invalidCounter, designation, e);

                logSessionBeanLocal.addLog("Add employee", "Employee account created: " + userId, "addEmployee.xhtml", userSessionManagerBean.getUserId());

                ArrayList<String> al = new ArrayList<String>();
                al.add("Account created");
                al.add("You have successfully created the user account.");
                al.add("Click on the link to return to ");
                al.add("continue");
                al.add("Web_IT/addEmployee.xhtml");
                userSessionManagerBean.setSelectedItem(al);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort() + "/MerlionERP-war/success.xhtml");
            } catch (Exception ex) {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
            }
        } else {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "A user account with the same user id already exists.", ""));
        }
    }

    public void resetPassword() {
        try {
            String temp = Long.toHexString(Double.doubleToLongBits(Math.random())).substring(0, 8);
            setUserPassword(temp);
            Calendar cal = Calendar.getInstance();
            Date d = new Date();
            cal.setTime(d);
            setPasswordExpiry(d);
            employeeSessionBeanLocal.updatePassword(userId, userPassword, passwordExpiry);
            EmailManager em = new EmailManager();
            em.sendEmail("[REQUEST] Password reset", "Dear " + userId + ",\n\n" + "We have received your request on " + cal.getTime().toString() + " and we have reset your password.\n\nYou can access your account using the new ONE-TIME-PASSWORD: " + temp
                    + "\n\nYou are required to change your password on the first account. \n\nShould you have any query, please reach us at 6886 2000. \n\nThank you. \n\nRegard,\nIT support team\n\n*This is a system generated message, no reply is required. ", "mf.merlionerp@gmail.com", emailAddress, "merlionfood");

            logSessionBeanLocal.addLog("Update employee", "Password reset: " + userId, "updateEmployee.xhtml", userSessionManagerBean.getUserId());
            ArrayList<String> al = new ArrayList<String>();
            al.add("Password reset completed");
            al.add("You have successfully reset the user account password. An email containing the new ONE-TIME-PASSWORD has been sent to the user.");
            al.add("Click on the link to return to ");
            al.add("continue");
            al.add("Web_IT/searchEmployee.xhtml?request=updateEmployee");
            userSessionManagerBean.setSelectedItem(al);

            FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                    + userSessionManagerBean.getServerPort() + "/MerlionERP-war/success.xhtml");
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
    }

    public void removeUser() {
        try {
            employeeSessionBeanLocal.deleteEmployee(employee.getUserId());
            ArrayList<String> al = new ArrayList<String>();
            logSessionBeanLocal.addLog("Delete employee", "Employee account removed: " + employee.getUserId(), "updateEmployee.xhtml", userSessionManagerBean.getUserId());
            al.add("Account removed");
            al.add("You have successfully removed user account. The user can no longer login with this account.");
            al.add("Click on the link to return to ");
            al.add("continue");
            al.add("Web_IT/searchEmployee.xhtml?request=updateEmployee");
            userSessionManagerBean.setSelectedItem(al);

            FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                    + userSessionManagerBean.getServerPort() + "/MerlionERP-war/success.xhtml");
        } catch (Exception ex) {
        }
    }

    public void edit(ActionEvent event) {
        userSessionManagerBean.setSelectedItem((Employee) employee);

        try {
            System.out.println(request);

            FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                    + userSessionManagerBean.getServerPort() + "/MerlionERP-war/Web_IT/" + request);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void doneUpdate(ActionEvent event) {
        try {
            String items[] = dob.split("/");
            dob = items[2] + "/" + items[1] + "/" + items[0];

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            Date d = sdf.parse(dob);

            employeeSessionBeanLocal.updateEmployee(employee.getUserId(), name, contactOffice, contactMobile, emailAddress, department, accountStatus, employee.getPasswordExpiry(), employee.getInvalidCounter(), designation, d);

            logSessionBeanLocal.addLog("Update employee", "Employee account updated: " + employee.getUserId(), "updateEmployee.xhtml", userSessionManagerBean.getUserId());
            ArrayList<String> al = new ArrayList<String>();
            al.add("Account updated");
            al.add("You have successfully updated user account. The changes will be reflected on the next login.");
            al.add("Click on the link to return to ");
            al.add("continue");
            al.add("Web_IT/searchEmployee.xhtml?request=updateEmployee");
            userSessionManagerBean.setSelectedItem(al);

            FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                    + userSessionManagerBean.getServerPort() + "/MerlionERP-war/success.xhtml");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

//    public void getEmployeeWelcome(String id) {
//
//        String sql = "SELECT employee.userId AS employee_userId, employee.userPassword AS employee_userPassword "
//                + "FROM employee AS employee "
//                + "WHERE employee.userId='" + id + "'";
//        String file = "EmployeeWelcome.jasper";
//        try {
//            ResultSet result;
//            result = merlionerp_db.getConnection().prepareStatement(sql).executeQuery();
//            JRResultSetDataSource resultSet;
//            resultSet = new JRResultSetDataSource(result);
//            FacesContext context;
//            context = FacesContext.getCurrentInstance();
//            HttpServletResponse response;
//            response = (HttpServletResponse) context.getExternalContext().getResponse();
//            InputStream readStream;
//            readStream = context.getExternalContext().getResourceAsStream("/Jasper_reports/" + file);
//            response.setContentType("application/pdf");
//
//
//            ServletOutputStream outputStream;
//            outputStream = response.getOutputStream();
//            HashMap parameters = new HashMap();
//            parameters.put("IMAGEPATH", "http://localhost:8080/MerlionERP-war/Jasper_reports/merlionV1.jpg");
//
//            JasperRunManager.runReportToPdfStream(readStream, outputStream, parameters, resultSet);
//            outputStream.flush();
//            outputStream.close();
//        } catch (Exception ex) {
//        }
//
//
//    }
    /**
     * @return the loadUserAC
     */
    public String getLoadUserAC() {
        Employee employee = (Employee) userSessionManagerBean.getSelectedItem();

        if (employee != null) {
            userId = employee.getUserId();
            asroles = "";

            ArrayList<AccessControl> acl = new ArrayList<AccessControl>();

            for (AccessRole ar : employee.getAccessRoles()) {
                asroles += ar.getRoleType() + ",";
                for (AccessControl ac : ar.getAccessControls()) {
                    acl.add(ac);
                }
            }

            HashSet set = new HashSet(acl);
            acl.clear();
            acl.addAll(set);

            ascontrol = "";
            for (AccessControl ac2 : acl) {
                ascontrol += ac2.getTitle() + ",";
            }
        }

        return null;
    }

    /**
     * @param loadUserAC the loadUserAC to set
     */
    public void setLoadUserAC(String loadUserAC) {
        this.loadUserAC = loadUserAC;
    }

    public void back(ActionEvent event) {
        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                    + userSessionManagerBean.getServerPort() + "/MerlionERP-war/searchEmployee.xhtml?request=viewUserAccessControl");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void backViewEmployee(ActionEvent e) {
        try {
            if (e.getComponent().getId().equals("btnBack")) {
                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + getUserSessionManagerBean().getServerName() + ":"
                        + getUserSessionManagerBean().getServerPort()
                        + "/MerlionERP-war/Web_IT/searchEmployee.xhtml?request=viewEmployee"); //go back to searchEmployee.xhtml
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
